# -*- coding: utf-8 -*-

# @File  : demo.py
# @Author: Lomo
# @Site  : lomo.space
# @Date  : 2021-09-19
# @Desc  :
# 参考文档: https://www.cnblogs.com/zhangxinqi/p/9106265.html


import psutil


if __name__ == "__main__":
    # 以下为 mac 本地测试结果
    # 获取 cpu 个数
    print(psutil.cpu_count(logical=True))  # 8
    print(psutil.cpu_count(logical=False))  # 4

    # cpu 利用率
    print(psutil.cpu_percent(percpu=True))  # [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

    # cpu 时间花费
    print(psutil.cpu_times())  # scputimes(user=349923.72, nice=0.0, system=251807.68, idle=7478612.14)
    # [scputimes(user=95708.83, nice=0.0, system=79716.36, idle=834656.06),
    # scputimes(user=8153.16, nice=0.0, system=8288.79, idle=993631.36),
    # scputimes(user=86081.37, nice=0.0, system=59441.88, idle=864552.0),
    # scputimes(user=7696.46, nice=0.0, system=6894.06, idle=995482.42),
    # scputimes(user=73204.83, nice=0.0, system=47243.04, idle=889626.56),
    # scputimes(user=7571.32, nice=0.0, system=6047.0, idle=996454.23),
    # scputimes(user=64015.79, nice=0.0, system=38725.15, idle=907332.76),
    # scputimes(user=7531.46, nice=0.0, system=5480.92, idle=997059.79)]
    print(psutil.cpu_times(percpu=True))

    print(psutil.pids())  # 以列表的形式返回当前正在运行的进程

    print(psutil.pid_exists(10))  # False; 判断给定的pid是否存在

    print(psutil.Process(1).name())  # 获取某个进程 pid(1) 的进程名
    print(psutil.Process(1).create_time())  # 1630760378.169981; 获取某个进程 pid(1) 的创建时间

    print(psutil.Process(99280).num_fds())  # 26; 获取某个进程 pid(99280) 打开的文件个数
    print(psutil.Process(99280).num_threads())  # 14; 获取某个进程 pid(99280) 子进程个数
    print(psutil.Process(99280).is_running())  # True; 14 获取某个进程 pid(99280) 是否运行中

    process = psutil.Process(99280)
    # psutil.Process(pid=99280, name='Code Helper (Renderer)', status='running', started='2021-09-13 17:25:43')
    print(process)
    print(process.exe())  # 进程 bin 路径
    print(process.cwd())  # 进程工作目录的绝对路径
    print(process.uids())  # puids(real=502, effective=502, saved=502)
    print(process.gids())  # puids(real=20, effective=20, saved=20)

    # snetio(bytes_sent=7913982678, bytes_recv=44700186567, packets_sent=25395103,
    # packets_recv=40584643, errin=0, errout=0, dropin=0, dropout=0)
    print(psutil.net_io_counters())

    # 【进程内存】 rss\vms 信息
    print(process.memory_info())  # pmem(rss=24244224, vms=43379965952, pfaults=42303, pageins=4)
    # 进程的内存利用率
    print(process.memory_percent())  # 0.1413583755493164

    print(process.cpu_percent())  # cpu 使用率

    # io
    # print(psutil.Process(480).io_counters())  # 可能该 pid 没有 io 相关操作导致报错

    # sdiskio(read_count=40375561, write_count=28136326,
    # read_bytes=902754061824, write_bytes=728129847296, read_time=15703091, write_time=5867771)
    print(psutil.disk_io_counters())  # 磁盘 io

    print(psutil.getloadavg())  # 系统负载, 分别表示 1 分钟， 5 分钟， 15 分钟的系统负载情况

    print(psutil.virtual_memory())







